package com.morn.fanfou.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TimerTask;

import android.content.Context;
import android.database.ContentObserver;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ListFragment;
import android.support.v4.content.AsyncTaskLoader;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.morn.fanfou.ConversationActivity;
import com.morn.fanfou.FanfouApplication;
import com.morn.fanfou.R;
import com.morn.fanfou.api.Fanfou;
import com.morn.fanfou.model.Message;
import com.morn.fanfou.util.Constants;
import com.morn.fanfou.widget.ConversationAdapter;

public class ConversationFragment extends ListFragment {

	private static int count = 0;

	private BaseAdapter adapter;

	private String otherId;

	private List<Message> messagelist = new ArrayList<Message>();

	private Fanfou fanfou;

	private class MessageObserver extends ContentObserver {

		public MessageObserver(Handler handler) {
			super(handler);

		}

		@Override
		public void onChange(boolean selfChange) {
			Toast.makeText(ConversationFragment.this.getActivity(), count + "",
					Toast.LENGTH_SHORT).show();

		}

	}

	// private MessageObserver messageObserver;

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		// messageObserver = new MessageObserver(new Handler());

		otherId = ((ConversationActivity) this.getActivity()).getOtherId();

		fanfou = ((FanfouApplication) this.getActivity().getApplication())
				.getFanfou();
		adapter = new ConversationAdapter(this.getActivity(), messagelist,
				otherId);
		this.setListAdapter(adapter);
		this.setEmptyText(getActivity().getString(R.string.empty));
		Bundle bundle = new Bundle();
		bundle.putString("otherId", otherId);

	}

	@Override
	public void onDestroy() {

		super.onDestroy();
	}

	public void addMessage(Message message) {
		messagelist.add(message);
		adapter.notifyDataSetChanged();
		ConversationFragment.this.getListView()
				.setSelection(messagelist.size());
		new SendMessageAsyncTask().execute(message);

	}

	TimerTask messageTask = new TimerTask() {

		@Override
		public void run() {
			try {
				count++;
				// ConversationFragment.this.getActivity().getContentResolver()
				// .notifyChange(Constants.MESSAGE_ADD_URI, messageObserver);
				Thread.sleep(5000);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}

	};

	private class SendMessageAsyncTask extends
			AsyncTask<Object, Object, String> {

		private Message newMessage;

		private Message oldMessage;

		@Override
		protected String doInBackground(Object... params) {
			oldMessage = (Message) params[0];
			String error = "OK";
			try {
				newMessage = fanfou.sendMessage(oldMessage.getRecipient_id(),
						oldMessage.getText(), oldMessage.getRecipient_id());
			} catch (Exception e) {
				e.printStackTrace();
				error = e.getMessage();
			}

			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			if ("OK".equals(result)) {
				if (newMessage != null)
					Collections.replaceAll(messagelist, oldMessage, newMessage);
				adapter.notifyDataSetChanged();
				ConversationFragment.this.getListView().setSelection(
						messagelist.size());
			} else {
				Toast.makeText(ConversationFragment.this.getActivity(), result,
						Toast.LENGTH_SHORT).show();
			}

		}
	}

	// @Override
	// public Loader<List<Message>> onCreateLoader(int id, Bundle args) {
	// Log.i(Constants.TAG, "args=" + args.getString("otherId"));
	// return new MessageLoader(this.getActivity(), args.getString("otherId"));
	// }
	//
	// @Override
	// public void onLoadFinished(Loader<List<Message>> loader, List<Message>
	// data) {
	// Log.i(Constants.TAG, "list<Message> size()=" + data.size());
	// Collections.sort(data, new Message.ComparatorMessage());
	// messagelist.clear();
	// messagelist.addAll(data);
	// adapter.notifyDataSetChanged();
	// ConversationFragment.this.getListView()
	// .setSelection(messagelist.size());
	// }
	//
	// @Override
	// public void onLoaderReset(Loader<List<Message>> loader) {
	// Log.i(Constants.TAG, "onLoaderReset--------");
	//
	// }

	static class MessageLoader extends AsyncTaskLoader<List<Message>> {

		private Fanfou fanfou;

		private String otherId;

		public MessageLoader(Context context, String otherId) {
			super(context);
			fanfou = ((FanfouApplication) context.getApplicationContext())
					.getFanfou();
			this.otherId = otherId;
			Log.i(Constants.TAG, "MessageLoader Create");
		}

		@Override
		protected void onStartLoading() {
			Log.i(Constants.TAG, "MessageLoader onStartLoading");
			forceLoad();
		}

		@Override
		public void deliverResult(List<Message> data) {
			super.deliverResult(data);
			Log.i(Constants.TAG, "MessageLoader deliverResult");
		}

		@Override
		public List<Message> loadInBackground() {
			Log.i(Constants.TAG, "otherId=" + otherId);
			try {
				// List<Message> messageList = fanfou.getConversation(otherId,
				// null, null, null);
				// return messageList;
				return null;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
	}

}
